package com.house.framework.aspectj;

import com.house.common.annotation.DataScope;
import com.house.common.core.domain.BaseEntity;
import com.house.common.core.domain.entity.Role;
import com.house.common.core.domain.entity.User;
import com.house.common.core.domain.model.LoginUser;
import com.house.common.utils.SecurityUtils;
import com.house.common.utils.StringUtils;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 数据过滤处理
 *
 * @author ruoyi
 */
@Aspect
@Component
@Slf4j
public class DataScopeAspect {
    /**
     * 管理员数据键值
     */
    public static final String DATA_SCOPE_ADMIN = "admin";

    /**
     * 普通用户数据键值
     */
    public static final String DATA_SCOPE_COMMON = "common";

    /**
     * VIP用户数据键值
     */
    public static final String DATA_SCOPE_VIP = "vip";

    /**
     * 房屋中介数据键值
     */
    public static final String DATA_SCOPE_MEDIUM = "medium";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            User currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser)) {
                dataScopeFilter(joinPoint, currentUser, controllerDataScope.tableAlias());
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user      用户
     */
    public static void dataScopeFilter(JoinPoint joinPoint, User user, String tableAlias) {
        StringBuilder sqlString = new StringBuilder();

        String name = joinPoint.getSignature().getName();
        log.info("DataScope增强的方法名为:{}", name);

        for (Role role : user.getRoles()) {
            String dataScope = role.getRoleKey();
            if (DATA_SCOPE_ADMIN.equals(dataScope)) {
                if ("selectHouseList".equals(name)) {
                    //房屋信息
                    sqlString.append(StringUtils.format(
                            " where 1=1"));
                } else {
                    sqlString = new StringBuilder();
                    break;
                }
            } else if (DATA_SCOPE_COMMON.equals(dataScope)) {
                if ("selectContractList".equals(name)) {
                    //合同
                    sqlString.append(StringUtils.format(
                            " where b_user_id = {} ", user.getUserId()));
                } else if ("selectHouseList".equals(name)) {
                    //房屋信息
                    sqlString.append(StringUtils.format(
                            " where {}.is_rental = 1 ", tableAlias));
                } else {
                    //其他通用
                    sqlString.append(StringUtils.format(
                            " where user_id = {} ", user.getUserId()));
                }
            } else if (DATA_SCOPE_MEDIUM.equals(dataScope)) {
                sqlString.append(StringUtils.format(" left join medium m on m.house_id = {}.house_id left join user u on u.user_id =  m.user_id where u.user_id = {}",
                        tableAlias, user.getUserId()));
            }
        }

        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_SCOPE, sqlString.substring(1));
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(DATA_SCOPE, "");
        }
    }
}
